import {
  getAdoptPage,
  searchAdoptAccountList,
  searchTreeOrganization,
} from '@/services/api/api-cues-adopt';
import { FileImageOutlined, MessageOutlined, PaperClipOutlined } from '@ant-design/icons';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Popover, Space, Tag, Typography, message } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import DetailsActive from '../../active/components/DetailsActive';
import DetailsSubmit from '../../topic/topic/components/DetailsSubmit';
import { findTagColor } from '@/utils/findTagColor';

interface TableAdoptProps {
  onDetails: (id: string, name: string) => void;
}

const TableAdopt: React.FC<TableAdoptProps> = (props) => {
  const { onDetails } = props;
  const access = useAccess();
  const actionRef = useRef<ActionType>();

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);

  const [adoptAccounts, setAdoptAccountsState] = useState<any[]>([]);

  /**
   * 加载 组织 列表
   * @param key
   */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) { }
  };

  /**
   * 加载 收录人 列表
   * @param key
   */
  const searchAdoptAccountListData = async () => {
    try {
      const response = await searchAdoptAccountList({
        filter: 0,
      });
      if (response.code === 0) {
        setAdoptAccountsState(
          response.data.map((item) => {
            return {
              value: item.accountId,
              label: `${item.accountName} - ${item.count}`,
            };
          }),
        );
      }
    } catch (error) { }
  };

  useEffect(() => {
    if (access.线索上报x主动报送x选题列表x收录线索) {
      treeOrganizationData();
    }

    if (access.线索上报x主动报送x配置x管理员) {
      searchAdoptAccountListData();
    }
  }, []);

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <ProTable<CuesAdoptData.AdoptVo>
      columns={[
        {
          title: '上报单位',
          hideInTable: true,
          hideInSearch: access.线索上报x主动报送x选题列表x上报线索,
          key: 'organizationIds',
          valueType: 'cascader',
          colSize: 4,
          fieldProps: {
            multiple: true,
            options: articleOrganizations,
            showSearch: { filter },
          },
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
          valueType: 'select',
          width: '80px',
          align: 'center',
          fixed: 'left',
          valueEnum: {
            1: { text: '线索征集' },
            2: { text: '主动报送' },
          },
          render: (_, record) => (
            <Space>
              <Tag color={record.type === 1 ? 'blue' : 'green'} key="type">
                {record.type === 1 ? '线索征集' : '主动报送'}
              </Tag>
            </Space>
          ),
        },
        {
          title: '上报线索',
          dataIndex: 'articleName',
          // copyable: true,
          ellipsis: true,
          width: '200px',
          align: 'center',
          key: 'articleName',
          fixed: 'left',
          render: (dom, record, _index, action) => {
            return (
              <div
                style={{
                  textAlign: 'left',
                  textOverflow: 'ellipsis',
                  whiteSpace: "nowrap",
                  overflow: 'hidden'
                }}
              >
                {record.isImage === 1 ? <FileImageOutlined /> : <></>}
                {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
                {record.type === 1 && access.线索上报x选题计划x选题列表x详情页面 ? (
                  <DetailsSubmit
                    table={"adopt"}
                    tableAdoptAccountId={record.adoptAccountId}
                    id={record?.articleId}
                    name={record?.articleName}
                    onRefurbish={() => {
                      actionRef.current?.reload();
                    }}
                  />
                ) : record.type === 2 && access.线索上报x选题计划x选题列表x详情页面 ? (
                  <DetailsActive
                    table={"adopt"}
                    tableAdoptAccountId={record.adoptAccountId}
                    id={record?.articleId}
                    name={record?.articleName}
                    onRefurbish={() => {
                      action?.reload();
                    }}
                  />
                ) : (
                  <a
                    onClick={() => {
                      message.error('无访问权限');
                    }}
                  >
                    {record.articleName}
                  </a>
                )}
              </div>
            );
          },
        },
        {
          title: '行业',
          dataIndex: 'articleIndustryName',
          key: 'articleIndustryName',
          width: '80px',
          align: 'center',
          search: false,
        },
        {
          title: '单位',
          key: 'articleOrganizationTopName',
          dataIndex: 'articleOrganizationTopName',
          width: '180px',
          search: false,
          align: 'center',
          render: (_, row) => (
            <div
              style={{
                textAlign: 'left',
                marginLeft: '8px'
              }}
            >
              <Tag color={findTagColor(row.articleOrganizationTopName)}>{row.articleOrganizationTopName}</Tag>
              {row.articleOrganizationName}
            </div>
          ),
        },
        {
          title: '新闻联络人',
          dataIndex: 'articleAccountName',
          // copyable: true,
          ellipsis: true,
          search: false,
          width: '80px',
          align: 'center',
          key: 'articleAccountName',
        },
        {
          title: '收录人',
          hideInTable: true,
          hideInSearch: !access.线索上报x主动报送x配置x管理员,
          key: 'adoptAccountIds',
          valueType: 'select',
          fieldProps: {
            mode: 'multiple',
            options: adoptAccounts,
          },
        },
        {
          title: '指令状态',
          dataIndex: 'adoptIsInstruct',
          // copyable: true,
          ellipsis: true,
          search: false,
          width: '50px',
          align: 'center',
          key: 'adoptIsInstruct',
          render: (_, record) => (
            <>
              <Space>
                <Tag color={record.adoptCancelAccountId ? 'red' : 'green'}>
                  {record.adoptCancelAccountId ? '取消' : '进行'}
                </Tag>
              </Space>
            </>
          ),
        },
        {
          title: '指令类型',
          dataIndex: 'adoptIsInstruct',
          // copyable: true,
          ellipsis: true,
          search: false,
          width: '50px',
          align: 'center',
          key: 'adoptIsInstruct',
          render: (_, record) => (
            <>
              <Space>
                <Tag color={record.adoptIsInstruct === 0 ? 'green' : 'orange'}>
                  {record.adoptIsInstruct === 0 ? '自主' : '指令'}
                </Tag>
              </Space>
              <Popover content={<>
                <Typography.Text type="warning">{record.adoptInstructAccountName}</Typography.Text>
                <Typography.Paragraph>
                  <blockquote>{record.adoptInstructDescribes}</blockquote>
                </Typography.Paragraph></>}>
                {record.adoptIsInstruct !== 0 && record.adoptInstructDescribes != null && record.adoptInstructDescribes != "" && <MessageOutlined />}
              </Popover>
            </>
          ),
        },
        {
          title: '收录人',
          dataIndex: 'adoptAccountName',
          // copyable: true,
          ellipsis: true,
          search: false,
          width: '80px',
          align: 'center',
          key: 'adoptAccountName',
        },
        {
          title: '指令人',
          dataIndex: 'adoptInstructAccountName',
          // copyable: true,
          ellipsis: true,
          search: false,
          width: '80px',
          align: 'center',
          key: 'adoptInstructAccountName',
        },
        {
          title: '收录日期',
          dataIndex: 'createdTimes',
          key: 'createdTimes',
          valueType: 'dateRange',
          hideInTable: true,
          fieldProps: {
            allowClear: true,
            placeholder: ['开始日期', '结束日期'],
            format: 'YYYY-MM-DD',
            ranges: {
              今日: [moment(), moment()],
              本月: [moment().startOf('month'), moment().endOf('month')],
              上月: [
                moment().startOf('month').subtract(1, 'months'),
                moment().endOf('month').subtract(1, 'months'),
              ],
              最近7天: [moment().subtract(6, 'days'), moment()],
              最近60天: [moment().subtract(59, 'days'), moment()],
              最近90天: [moment().subtract(89, 'days'), moment()],
            },
          },
        },
        {
          title: '收录时间',
          dataIndex: 'createdTime',
          key: 'createdTime',
          width: '120px',
          align: 'center',
          search: false,
        },
        // {
        //   title: '是否录用',
        //   dataIndex: 'isAdopt',
        //   key: 'isAdopt',
        //   valueType: 'select',
        //   width: '80px',
        //   align: 'center',
        //   fixed: 'right',
        //   valueEnum: {
        //     0: { text: '未录用' },
        //     1: { text: '已录用' },
        //   },
        //   hideInSearch: true,
        //   render: (_, record) => (
        //     <Space>
        //       <Tag color={record.isAdopt === 0 ? '#F9CF59' : '#1AA15F'} key="isAdopt">
        //         {record.isAdopt === 0 ? '未录用' : '已录用'}
        //       </Tag>
        //     </Space>
        //   ),
        // },
        // {
        //   title: '评分',
        //   dataIndex: 'score',
        //   key: 'score',
        //   width: '50px',
        //   align: 'center',
        //   fixed: 'right',
        //   search: false,
        //   hideInTable: !access.线索上报x选题计划x选题列表x评分线索,
        // },
      ]}
      actionRef={actionRef}
      request={async (params = {}) => {
        if (params.organizationIds) {
          const organizationParentIds: string[] = [];
          let organizationIds: string[] = [];

          params.organizationIds.forEach((item: string | any[]) => {
            if (item.length === 1) {
              organizationParentIds.push(item[0]);
            } else if (item.length > 1) {
              organizationIds.push(item[1]);
            }
          });
          organizationParentIds.forEach((id) => {
            const ids = articleOrganizations.find((item) => item.id === id).children;
            organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
          });
          params.articleOrganizationIds = organizationIds;
        }

        const response = await getAdoptPage({
          ...params,
        });

        return Promise.resolve({
          data: response.data.data,
          total: response.data.total,
          success: response.code === 0,
        });
      }}
      rowKey="id"
      dateFormatter="string"
      bordered
      search={{
        collapsed: false,
        labelWidth: 'auto',
        collapseRender: false,
      }}
      // search={false}
      sticky
      scroll={{
        x: '1300px',
      }}
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
      }}
    />
  );
};

export default TableAdopt;
